//
//  AppendEvaluateVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/3/16.
//  Copyright © 2020 cat. All rights reserved.
//

#import "AppendEvaluateVC.h"
#import "TZImagePickerController.h"
#import <Qiniu/QiniuSDK.h>
#import "YBStorageObj.h"
@interface AppendEvaluateVC ()<TZImagePickerControllerDelegate>
{
    UIScrollView *_backScroll;
    MyTextView *evaluateText;
    UIView *_photoView;
    CGFloat imgWidth;
    NSMutableArray *imageArray;
    UIButton *imageBtn;
    UIButton *videoBtn;
    UIButton *subVideoBtn;

    NSString *videoPath;
    UIImage *videoCoverImage;
    NSString *videoCorverStr;
    NSString *videoHerfStr;

    NSString *picThumbsStr;
    NSMutableArray *imageUrlArray;
}
@end

@implementation AppendEvaluateVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Normal_BackColor;
    self.titleL.text = YZMsg(@"发表追评");
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"发布") forState:0];
    [self.rightBtn setTitleColor:Pink_Cor forState:0];
    imgWidth = (_window_width - 75)/4;
    imageArray = [NSMutableArray array];

    picThumbsStr = @"";
    videoHerfStr = @"";
    videoCorverStr =@"";
    videoPath = @"";
    
    [self createUI];

}
-(void)createUI{
    _backScroll = [[UIScrollView alloc]init];
    _backScroll.frame = CGRectMake(0, 64+statusbarHeight, _window_width, _window_height);
    _backScroll.backgroundColor = Normal_SubColor;
    [self.view addSubview:_backScroll];
    
    UIImageView *headImg = [[UIImageView alloc]init];
    headImg.frame = CGRectMake(15, 10, 60, 60);
    headImg.layer.cornerRadius = 5;
    headImg.layer.masksToBounds = YES;
    headImg.contentMode = UIViewContentModeScaleAspectFill;
    [headImg sd_setImageWithURL:[NSURL URLWithString:self.model.spec_thumb]];
    [_backScroll addSubview:headImg];
    
    UILabel *goodsname = [[UILabel alloc]init];
    goodsname.frame = CGRectMake(headImg.right+10, headImg.top+10, 200, 20);
    goodsname.font = [UIFont systemFontOfSize:14];
    goodsname.textColor = [UIColor whiteColor];
    goodsname.text = self.model.goods_name;
    [_backScroll addSubview:goodsname];
    
    UILabel *specname = [[UILabel alloc]init];
    specname.frame = CGRectMake(headImg.right+10, goodsname.bottom+5, 200, 20);
    specname.font = [UIFont systemFontOfSize:13];
    specname.textColor = Normal_TextColor;
    specname.text =[NSString stringWithFormat:@"%@ x%@",self.model.spec_name,self.model.nums];
    [_backScroll addSubview:specname];

    [PublicObj lineViewWithFrame:CGRectMake(0, headImg.bottom+15, _window_width, 1) andColor:Line_Cor andView:_backScroll];
    
    evaluateText = [[MyTextView alloc]init];
    evaluateText.frame = CGRectMake(10, headImg.bottom+30, _window_width-20, 125);
    evaluateText.placeholderColor = Normal_TextColor;
    evaluateText.placeholder =YZMsg(@"已经用了一段时间了,有更多宝贝使用心得？分享给想买的他们吧");
    evaluateText.font = [UIFont systemFontOfSize:14];
    evaluateText.backgroundColor = Normal_SubColor;
    evaluateText.textColor = [UIColor whiteColor];
    [_backScroll addSubview:evaluateText];

    
    _photoView = [[UIView alloc]init];
    _photoView.frame = CGRectMake(0, evaluateText.bottom, _window_width, imgWidth+10);

     [_backScroll addSubview:_photoView];
     NSArray *arr = @[@"添加图片",@"添加视频"];
    NSArray *titlearr = @[YZMsg(@"添加图片"),YZMsg(@"添加视频")];

     imageBtn = [UIButton buttonWithType:0];
     imageBtn.frame = CGRectMake(15,0, imgWidth, imgWidth);
     CAShapeLayer *border = [CAShapeLayer layer];
     //虚线的颜色
     border.strokeColor = Normal_TextColor.CGColor;
     //填充的颜色
     border.fillColor = [UIColor clearColor].CGColor;
     //设置路径
     border.path = [UIBezierPath bezierPathWithRect:imageBtn.bounds].CGPath;
     border.frame = imageBtn.bounds;
     //虚线的宽度
     border.lineWidth = 1.f;
     //虚线的间隔
     border.lineDashPattern = @[@4, @2];
     [imageBtn.layer addSublayer:border];
     
     [imageBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"evaluate%@",arr[0]]] forState:0];
     [imageBtn setTitle:titlearr[0] forState:0];
     [imageBtn setTitleColor:Normal_TextColor forState:0];
     imageBtn.titleLabel.font = [UIFont systemFontOfSize:10];
     imageBtn = [PublicObj setUpImgDownText:imageBtn];
     imageBtn.tag = 1000;
     [imageBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
     [_photoView addSubview:imageBtn];

     
     videoBtn = [UIButton buttonWithType:0];
     videoBtn.frame = CGRectMake(15+(1%4)*(imgWidth + 15),0, imgWidth, imgWidth);
     CAShapeLayer *border2 = [CAShapeLayer layer];
    //虚线的颜色
     border2.strokeColor = Normal_TextColor.CGColor;
    //填充的颜色
     border2.fillColor = [UIColor clearColor].CGColor;
    //设置路径
     border2.path = [UIBezierPath bezierPathWithRect:videoBtn.bounds].CGPath;
     border2.frame = videoBtn.bounds;
    //虚线的宽度
     border2.lineWidth = 1.f;
    //虚线的间隔
     border2.lineDashPattern = @[@4, @2];
     [videoBtn.layer addSublayer:border2];
    
     [videoBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"evaluate%@",arr[1]]] forState:0];
     [videoBtn setTitle:titlearr[1] forState:0];
     [videoBtn setTitleColor:Normal_TextColor forState:0];
     videoBtn.titleLabel.font = [UIFont systemFontOfSize:10];
     videoBtn = [PublicObj setUpImgDownText:videoBtn];
     videoBtn.tag = 1001;
     [videoBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
     [_photoView addSubview:videoBtn];
    
    _backScroll.size = CGSizeMake(_window_width, _photoView.bottom+10);

}
-(void)imageBtnClick:(UIButton *)sender
{
        if (sender.tag == 1000) {
            TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:5-imageArray.count delegate:self];
            imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
            imagePC.modalPresentationStyle = 0;
            imagePC.showSelectBtn = YES;
            imagePC.allowCrop = NO;
            imagePC.allowPickingOriginalPhoto = NO;
            imagePC.oKButtonTitleColorNormal = Pink_Cor;
            imagePC.allowTakePicture = YES;
            imagePC.allowTakeVideo = NO;
            imagePC.allowPickingVideo = NO;
            imagePC.allowPickingMultipleVideo = NO;
    //        imagePC.takePictureImageName = @"ybtakePicture80";

            [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
        }else if (sender.tag == 1001){
            TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
            imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
            imagePC.modalPresentationStyle = 0;
            imagePC.showSelectBtn = NO;
            imagePC.allowCrop = NO;
            imagePC.allowPickingOriginalPhoto = NO;
            imagePC.oKButtonTitleColorNormal = Pink_Cor;
            imagePC.allowPickingImage = NO;
            imagePC.allowTakePicture = NO;
            imagePC.allowTakeVideo = YES;
            imagePC.allowPickingVideo = YES;
            imagePC.allowPickingMultipleVideo = NO;
            imagePC.videoMaximumDuration = live_MAX_RECORD_TIME;//MAX_RECORD_TIME;
    //        imagePC.takePictureImageName = @"ybtakevideo80";
            [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
        }

}
#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    NSLog(@"-dsddddddddd--%@\n===%@",asset,coverImage);
    
    [MBProgressHUD showMessage:@""];
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        if (outputPath) {
            [MBProgressHUD hideHUD];
            videoPath = outputPath;
            videoCoverImage = coverImage;
            [self addVideoimage];
        }else{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:YZMsg(@"请重新选择(iCloud视频请先在本地相册下载后上传)")];
        }

    } failure:^(NSString *errorMessage, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:errorMessage];
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSLog(@"------多选择图片--：%@",photos);
    [imageArray addObjectsFromArray:photos];
    [self setImageFrame];
}
-(void)setImageFrame{

    for (UIButton *btn in _photoView.subviews) {
        if (btn.tag >=3000) {
            [btn removeFromSuperview];
        }
    }
    if (imageArray.count > 0) {
        if (imageArray.count < 3) {
            _photoView.size= CGSizeMake(_window_width, imgWidth+10);

        }else if (imageArray.count>=3){
            _photoView.size= CGSizeMake(_window_width, imgWidth*2+20);

        }
        for (int i = 0; i < imageArray.count ; i ++) {
            UIButton *btn = [UIButton buttonWithType:0];
            btn.backgroundColor = RGB(250, 250, 250);
            if (i < 4) {
                btn.frame = CGRectMake(15+(i%4)*(imgWidth + 15), 0, imgWidth, imgWidth);

            }else{
                btn.frame = CGRectMake(15+(i%4)*(imgWidth + 15), (imgWidth+10), imgWidth, imgWidth);
            }
            
            btn.tag = 3000+i;
            [btn setImage:imageArray[i] forState:0];
            [_photoView addSubview:btn];
            
            UIButton *delBtn = [UIButton buttonWithType:0];
            delBtn.frame = CGRectMake(imgWidth-25, 5, 20, 20);
            [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
            delBtn.tag = 4000+i;
            [delBtn addTarget:self action:@selector(delImageClick:) forControlEvents:UIControlEventTouchUpInside];
            [btn addSubview:delBtn];

        }
        if (imageArray.count < 3) {
            imageBtn.frame = CGRectMake(15+(imageArray.count%4)*(imgWidth + 15), 0, imgWidth, imgWidth);
            videoBtn.frame = CGRectMake(15+((imageArray.count+1)%4)*(imgWidth + 15), 0, imgWidth, imgWidth);

        }else if (imageArray.count == 3){
            imageBtn.frame = CGRectMake(15+(imageArray.count%4)*(imgWidth + 15), 0, imgWidth, imgWidth);
            videoBtn.frame = CGRectMake(15+((imageArray.count+1)%4)*(imgWidth + 15), (imgWidth+10), imgWidth, imgWidth);

        }else if (imageArray.count > 3){
            imageBtn.frame = CGRectMake(15+(imageArray.count%4)*(imgWidth + 15), (imgWidth+10), imgWidth, imgWidth);
            videoBtn.frame = CGRectMake(15+((imageArray.count+1)%4)*(imgWidth + 15), (imgWidth+10), imgWidth, imgWidth);

        }
    }else{
        imageBtn.frame = CGRectMake(15,0, imgWidth, imgWidth);
        videoBtn.frame = CGRectMake(15+(1%4)*(imgWidth + 15),0, imgWidth, imgWidth);
    }
    if (imageArray.count == 5) {
        imageBtn.hidden = YES;
        videoBtn.frame = CGRectMake(15+(imageArray.count%4)*(imgWidth + 15), (imgWidth+10), imgWidth, imgWidth);

    }else{
        imageBtn.hidden = NO;
    }
    _backScroll.size = CGSizeMake(_window_width, _photoView.bottom+10);

}
-(void)delImageClick:(UIButton *)sender{
    NSInteger index = sender.tag-4000;
    [imageArray removeObjectAtIndex:index];
    [self setImageFrame];
}
-(void)addVideoimage{
    subVideoBtn = [UIButton buttonWithType:0];
    subVideoBtn.frame = CGRectMake(0, 0, videoBtn.width, videoBtn.height);
    [subVideoBtn setBackgroundImage:videoCoverImage forState:0];
    [videoBtn addSubview:subVideoBtn];
    
    UIButton *delBtn = [UIButton buttonWithType:0];
    delBtn.frame = CGRectMake(subVideoBtn.width-25, 5, 20, 20);
    [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
    [delBtn addTarget:self action:@selector(delVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [subVideoBtn addSubview:delBtn];

}
-(void)delVideoClick{
    videoPath = @"";
    [subVideoBtn removeFromSuperview];
    subVideoBtn = nil;
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


-(void)clickNaviRightBtn{
    [MBProgressHUD showMessage:@""];
    NSLog(@"-------image:%@  \n===---video:%@",imageArray,videoPath);
    if (videoPath.length > 0 || imageArray.count > 0) {
        YBWeakSelf;
        [[YBStorageObj storageManeger]getCOSType:^(int code) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (code == 0) {
                    [weakSelf startUpload];
                }
            });
        }];
    }else{
        [self doUploadEvaluate];
    }
}

-(void)startUpload{
    YBWeakSelf;
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    //如果有视频或图片先上传视频
    if (videoPath.length > 0) {
        dispatch_group_async(group, queue, ^{
            NSData *imageData = UIImagePNGRepresentation(videoCoverImage);
            if (!imageData) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:YZMsg(@"请重新选择")];
                return;
            }
            UIImage *herfImg = [UIImage imageWithData:imageData];
            NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_action_video_cover.png"];
            [[YBStorageObj storageManeger]yb_storageImg:herfImg andName:imageName progress:^(CGFloat percent) {
                
            }complete:^(int code, NSString *key) {
                //图片成功
                videoCorverStr = key;
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });

        dispatch_group_async(group, queue, ^{
            //传视频
            NSString *videoName = [PublicObj getNameBaseCurrentTime:@"_action_video.mp4"];

            [[YBStorageObj storageManeger]yb_storageVideoOrVoice:videoPath andName:videoName progress:^(CGFloat percent) {
                
            } complete:^(int code, NSString *key) {
                videoHerfStr = key;

                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });

    }
    if (imageArray.count > 0) {
        imageUrlArray = [NSMutableArray array];
        picThumbsStr = @"";
        for (int i = 0; i < imageArray.count ; i ++) {
            
            UIImage *image =imageArray[i];
            NSData *imageData = UIImagePNGRepresentation(image);
            if (!imageData) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:YZMsg(@"图片错误")];
                return;
            }
            
            
            dispatch_group_async(group, queue, ^{
                NSString *imageName = [PublicObj getNameBaseCurrentTime:[NSString stringWithFormat:@"_action_image%d_cover.png", i]];
                [[YBStorageObj storageManeger]yb_storageImg:image andName:imageName progress:^(CGFloat percent) {
                    
                }complete:^(int code, NSString *key) {
                    [imageUrlArray addObject:key];
                    dispatch_semaphore_signal(semaphore);
                }];
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            });
        }
    }
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
                for (NSString *str in imageUrlArray) {
                    if (picThumbsStr.length == 0) {
                        picThumbsStr = str;
                    }else{
                        picThumbsStr = [NSString stringWithFormat:@"%@,%@",picThumbsStr,str];
                    }
                }
                [weakSelf doUploadEvaluate];
        });
        NSLog(@"任务完成执行");
    });

}

#pragma mark-----正式发布-----------
-(void)doUploadEvaluate{
    
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.appendEvaluateGoodsOrder"];
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.model.idStr,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.model.idStr,
                          @"content":evaluateText.text,
                          @"thumbs":picThumbsStr,
                          @"video_url":videoHerfStr,
                          @"video_thumb":videoCorverStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    
    [WYNetworking postWithUrl:@"Buyer.appendEvaluateGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code ==0) {
            [MBProgressHUD showError: msg];
            [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];

}

@end
